<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JavaScript 实现的待办事项</title>
</head>
<body>
<div class="container">
    <div id="addTask">
        <input type="text" placeholder="Task to be done.." autofocus>
        <button id="add">Add</button>
    </div>
    <div id="tasks"></div>
</div>

<script>
    document.querySelector('#add').onclick = function () {
        insertTask();
    }

    document.querySelector('#addTask input').addEventListener("keypress", function(event) {
        if (event.key === "Enter") {
            insertTask();
        }
    });

    function insertTask() {
        let taskInput = document.querySelector('#addTask input');

        if (taskInput.value.trim().length === 0) {
            alert("Please Enter a Task");
            taskInput.value = '';
        } else {
            document.querySelector('#tasks').innerHTML += `
                <div class="task">
                    <input class="cb" type="checkbox" />
                    <span class="taskName">
                        ${taskInput.value}
                    </span>
                    <button class="delete">
                        <i>x</i>
                    </button>
                </div>
            `;

            document.querySelectorAll(".delete").forEach(function (btnElement) {
                btnElement.onclick = function () {
                    this.parentNode.remove();
                }
            })

            document.querySelectorAll(".cb").forEach(function (checkboxElement) {
                checkboxElement.onclick = function () {
                    this.nextElementSibling.setAttribute("style", `text-decoration: ${this.checked ? 'line-through' : 'none'};`);
                }
            })

            taskInput.value = '';
        }
    }
</script>
</body>
</html>
